var socketOpen = false;
var socketMsgQueue = [];
// 引入配置
var config = require('../../../config');



Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatMsg:'',
    author:[
      {
        name:'Tommy',
        text:'Hello guys'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var url = config.service.channel.test1;
    console.log(url);
    wx.connectSocket({
      url: url
    });
    
    this.login();
    // func.login();
  },
  login: function () {
    //调用登录接口
    wx.login({
      success: function (e) {
        var openid = wx.getStorageSync('openid');
        if (!openid) {
          wx.request({
            url: config.service.loginUrl,
            data: {
              code: e.code
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              console.log('获取openid');
              console.log(res.data)
              wx.setStorageSync('openid', res.data.openid)
              // 连接服务器
            },
            fail: function (res) {
              console.log(res)
            }
          })
        } else {

        }
        console.log('wxlogin successd........');
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const _this = this;
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！');
      wx.sendSocketMessage({
        data: 'tommy'
      });
    });
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    });
    
    wx.onSocketMessage(function (res) {
      console.log('收到服务器内容：' + res.data)
      var now = _this.data.author;
      now.push({ name: 'Tommy', text: res.data });
      _this.setData({
        author: now
      });
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getSendTxt: function(e){
    this.setData({
      chatMsg: e.detail.value
    });
    // chatMsg = e.detail.value;
    
  },
  sendMsg: function(){
    // console.log(e);
    var chatMsg = this.data.chatMsg;
    if (chatMsg == ''){
      return false;
    }
    wx.sendSocketMessage({
      data: chatMsg
    });
    this.setData({
      chatMsg:''
    });
    
  }
});


function sendSocketMessage(msg) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data: msg
    });
  } else {
    socketMsgQueue.push(msg)
  }
}